/**
 * Created by huangxuehua on 2017/12/6.
 */
//$("header>a.goBack").click(function(){
//    window.history.back();
//})
var toast = new auiToast(); //初始化toast事件
var toastLoading = new auiToast({});   //懒加载
var mySwiper = undefined;
var xpHome = new Vue({
    el:'#app',
    data:{
      imgBaseUrl:nUrls.imgBaseUrl,
      afterSaleGoods:{},//售后产品信息
      content:"",//内容
      isChoose: null,//售后类型
      updataImgs:[],//上传图片
      cacheImgList:[],//获得缓存图片信息
      bigImgArr:[],//大图列表
      bigImgIndx:1,//当前显示图片
     isShowSwiper:false, //是否显示大图

    },
    methods:{
        getImage: function (url) {//加载图片  处理 url为空 加载出错
            if (url) {
                return xpHome.imgBaseUrl + url;
            }
        },
        initData:function(){
            var afterSaleInfo=window.localStorage.getItem("afterSaleInfo");
            if(afterSaleInfo){
                xpHome.afterSaleGoods=JSON.parse(afterSaleInfo)
                //console.log(xpHome.afterSaleGoods)
            }


        },
        getCacheImgInfo:function(){  //获取缓存图片信息
            var data={
                "data[rec_id]":xpHome.afterSaleGoods.rec_id
            }
            //console.log("--data[rec_id]--",data)
            $.ajax({
                url:nUrls.getAfterSaleCacheImgUrl,
                type:"POST",
                data:data,
                success:function(data){
                    var result=eval('('+data+')') ;//JOSN 数据转 JOSN对象
                    if(result && result.code===200){
                        xpHome.cacheImgList=result.data
                      //console.log("--- xpHome.cacheImgInfo--", xpHome.cacheImgList)
                        xpHome.getBeforeImages();//图片处理
                    }
                },
                error:function(){
                    console.log("获取缓存图片出错")
                }
            })
        },
        getBeforeImages:function(){//获取之前上传的图片
            var rec = xpHome.afterSaleGoods;
                var name = rec.rec_id;
                var goods_id = rec.goods_id;
                //console.log("- rec i--",name);
                if(xpHome.cacheImgList) {
                    var vImgs = xpHome.cacheImgList;
                    if (vImgs) {
                        for (var v = 0; v < vImgs.length; v++) {
                            var temp = {
                                "goodsid": goods_id,
                                "imgPath": nUrls.imgNativeUrl + vImgs[v].cservice_images,//绝对路径  全路径
                                "relativePath": vImgs[v].cservice_images, //相对路径
                                "recid": name,
                                "cservice_images_id": vImgs[v].cservice_images_id
                            };
                            xpHome.updataImgs.push(temp);
                            //console.log("-- xpHome.updataImgs-", temp)
                        }
                }
            }
        },
        commitDetail:function(){    //提交售后资料
            if(xpHome.isChoose == null){
                //alert("请选择售后类型");
                toast.custom({
                    title: "请输入售后类型",
                    html: '',
                    duration: 2000
                });
                return false;
            }
            if (!xpHome.content) { //内容
                //alert("请填写售后内容")
                toast.custom({
                    title: "请填写售后内容",
                    html: '',
                    duration: 2000
                });
                return;
            }
            var data={
                "data[content]":xpHome.content,  //售后内容
                "data[cservice_type]":xpHome.isChoose, //0换货 1维修
                "data[order_goods_id]	":xpHome.afterSaleGoods.rec_id// 货品Id
             }
            //console.log(xpHome.afterSaleGoods)
            $.ajax({
                url:nUrls.getAfterSale,
                type:"POST",
                data:data,
                success:function(data){
                    var result=eval('('+data+')') ;//JOSN 数据转 JOSN对象
                    if(result && result.code===200){
                     xpHome.afterSaleInfo=result.data
                        window.location.href="./after_sale_success.html"
                    }
                },
                error:function(){
                    console.log("服务器内部错误")
                }
            })

        },
        getTypeAndColor:function(target,type){   //分割字符串
            var temp = "";
            if(target){
                var arr = target.split("-----");
                if(arr.length == 2){
                    if(type == 0){//颜色
                        return arr[1];
                    }else{//型号
                        return arr[0];
                    }
                }
            }
            return temp;
        },
        chooseType:function(status){//维修状态

            xpHome.isChoose = status;
            //console.log( xpHome.isChoose )
        }, 
        addImage:function(e,it,recid,goodsid){//添加图片
            toastLoading.loading({
                title:"加载中",
            },function(ret){
            });
            var vv = $("#input_file").val();
            if(!vv){
                return ;
            }
            var reader = new FileReader();
            reader.onload = (function (file) {
                return function (e) {
                    var str = this.result;
                    compressImgByExactWidth(this.result,function(data){
                        requestData(nUrls.getAddImg,function(d){
                            //console.log("++++nUrls.getAddImg+++",d);
                            if(d && d.code == 200){
                                //服务器返回的是图片路径
                                var temp = {
                                    "goodsid":goodsid,
                                    "imgPath":nUrls.imgNativeUrl+d.data,//绝对路径  全路径
                                    "relativePath":d.data, //相对路径
                                    "cservice_images_id":d.cservice_images_id
                                };
                                xpHome.updataImgs.push(temp); //页面根据路径显示
                                //console.log("--xpHome.updataImgs-",xpHome.updataImgs)
                                toastLoading.hide();
                            }
                        },null,{imgStr:data,recid:recid,access_token:userInfo.access_token,goodsid:goodsid})
                    });
                };
            })(e.target.files[0]);
            reader.readAsDataURL(e.target.files[0])
        },
        delImage:function(num){  //删除图片
            var temp = xpHome.updataImgs[num];
            var rec=xpHome.afterSaleGoods
            var data={
                "data[cservice_images_id]" :temp.cservice_images_id,//商品id
                "data[imgPath]": temp.relativePath ,//图片路径
                "data[order_goods_id]":rec.rec_id,
                "access_token":userInfo.access_token,
            }
            //console.log("++delImage+++",data);
            $.ajax({
                url:nUrls.getDelImgUrl,
                type:"Post",
                data:data,
                success:function(data){
                    //console.log("----data[imgPath]-----",data)
                    var result=eval('('+data+')') ;//JOSN 数据转 JOSN对象
                    if(result && result.code===200){
                        xpHome.updataImgs.splice(num,1); //删除页面图片
                    }
                },
                error:function(){
                    console.log("删除图片出错")
                }
            })
        },
        showClick:function(index){
            xpHome.bigImgIndx = index + 1; //当前显示
            xpHome.showSwiper(index);
            //xpHome.bigImgShowSrc = $(this).attr("src");
        },
        showSwiper: function(idx) {    //图片滑动
            xpHome.isShowSwiper = true;
            document.documentElement.scrollTop = 0;
            document.body.scrollTop = 0;
            $("#commentBody").css("overflow","hidden");
            touchMoveCant("#mySwiper");
            this.$nextTick(function() {
                if(mySwiper) {
                    mySwiper.destroy();
                    mySwiper = undefined;
                }
                mySwiper = new Swiper("#mySwiper", {
                    direction: 'horizontal',
                    loop: false,
                    zoom: true,
                    onSlideChangeEnd: function(swiper) { //水平滑动切换
                        xpHome.bigImgIndx = swiper.activeIndex + 1; //滚动显示
                    }
                });
                if(idx === 0) {
                    mySwiper.slideTo(1, 0);
                    mySwiper.slideTo(0, 0);
                } else {
                    mySwiper.slideTo(idx, 0);
                }
            });
        },
        closeSwiper: function() {// 关闭大图
            $("#commentBody").css("overflow","auto");
            xpHome.isShowSwiper = false;
        },
        goOnLine:function(){  //断网刷新
            nUtils.onLine();
        }
    }
});

function compressImgByExactWidth(imgData,callback,width){
    if(!imgData)return;
    callback = callback || function(){};
    width = width || 320;//默认宽度320
    var canvas = document.createElement('canvas');
    var img = new Image();
    img.onload = function(){
        if(img.width > width) {//按最大高度等比缩放
            img.height *= width / img.width;
            img.width = width;
            //console.log("width",img.width)
        }
        var ctx = canvas.getContext("2d");
        ctx.clearRect(0, 0, canvas.width, canvas.height); // canvas清屏
        canvas.width = img.width;
        canvas.height = img.height;//重置canvans宽高
        ctx.drawImage(img, 0, 0, img.width, img.height); // 将图像绘制到canvas上
        callback(canvas.toDataURL("image/png"));
    };
    img.src = imgData;
}
//请求数据
function requestData(url,callback,getParams,postParams){
    if(!url){
        return;
    }
    var firstParam = true;
    if(getParams){
        if(url.indexOf('?')>-1){
            //说明之前已经拼接了参数
            firstParam = false;
        }
        for(var p in getParams){
            url +=firstParam?'?':'&';
            firstParam  = false;
            url += p + '=' + getParams[p];
        }
    }
    if(window.XMLHttpRequest) { // IE7+, Firefox, Chrome, Opera, Safari 代码
        xmlhttp = new XMLHttpRequest();
    } else { // IE6, IE5 代码
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function(){
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
            if(callback){
                //可能有安全隐患！！！！！！
                var data = eval('(' + xmlhttp.responseText + ')');
                callback(data);
            }
        }
    };
    xmlhttp.open("POST", url, true);
    xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    if(postParams) {
        firstParam = true;
        var postData = "";
        for(var p in postParams){
            if(!firstParam){
                postData+="&";
            }
            firstParam = false;
            postData += p+"="+postParams[p];
        }
    }
    xmlhttp.send(postData);
}

$(function(){
    $("#weixiu").click(function(){
        $("#weixiu").addClass("faPiaoType");
        $("#huanhuo").removeClass("faPiaoType");
    })
    $("#huanhuo").click(function(){
        $("#weixiu").removeClass("faPiaoType");
        $("#huanhuo").addClass("faPiaoType");
    })
    xpHome.initData();  //获取产品信息
    xpHome. getCacheImgInfo();//获取缓存图片信息
})
function touchMoveCant(ele){//ios 等其他型号手机 滑动问题
    document.querySelector(ele).addEventListener("touchmove", function(e){
        e.preventDefault();
    });
}
